package com.tiancheng.trade.settlement.service.settlement.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiancheng.trade.settlement.configuration.MidasSftpConfig;
import com.tiancheng.trade.settlement.enums.BillStatusEnum;
import com.tiancheng.trade.settlement.enums.PaymentChannelEnum;
import com.tiancheng.trade.settlement.mapper.settlement.*;
import com.tiancheng.trade.settlement.model.settlement.ClearBankDetailCmb;
import com.tiancheng.trade.settlement.model.settlement.ClearBankSummaryCmb;
import com.tiancheng.trade.settlement.model.settlement.SettlementBankBillDetail;
import com.tiancheng.trade.settlement.model.settlement.SettlementBankWaitBill;
import com.tiancheng.trade.settlement.service.settlement.IClearBankCmbService;
import com.tiancheng.trade.settlement.service.settlement.IClearingFileService;
import com.tiancheng.trade.settlement.util.CsvUtils;
import com.tiancheng.trade.settlement.util.JacksonJsonUtil;
import com.tiancheng.trade.settlement.util.ObjectConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 招行清分
 */
@Service
@Slf4j
public class ClearBankCmbService implements IClearBankCmbService {

    @Resource
    IClearingFileService clearingFileService;

    @Resource
    MidasSftpConfig midasSftpConfig;

    @Resource
    ClearBankDetailCmbBatch clearBankDetailCmbBatch;

    @Resource
    ClearBankDetailCmbMapper clearBankDetailCmbMapper;

    @Resource
    ClearBankSummaryCmbBatch clearBankSummaryCmbBatch;

    @Resource
    ClearBankSummaryCmbMapper clearBankSummaryCmbMapper;

    @Autowired
    SettlementBankBillDetailMapper settlementBankBillDetailMapper;

    @Autowired
    SettlementBankBillDetailBatch settlementBankBillDetailBatch;

    @Autowired
    SettlementBankWaitBillMapper settlementBankWaitBillMapper;

    @Autowired
    SettlementBankWaitBillBatch settlementBankWaitBillBatch;

    @Resource
    private RedissonClient redissonClient;

    @Autowired
    SettlementBillDataService settlementBillDataServiceImpl;

    @Resource
    JacksonJsonUtil jacksonJsonUtil;

    /**
     * 处理汇总数据
     *
     * @param date 对账日期，格式为yyyyMMdd,如20240417
     */
    public void handleSummaryData(String date) {
        String fileName = "BATCH_" + date + ".csv";
        fileBack("BATCH_", date);
        handleSummaryData(fileName, date);
    }

    /**
     * 处理明细数据
     *
     * @param date 对账日期，格式为yyyyMMdd,如20240417
     */
    public void handleDetailData(String date) {
        String fileName = "DETAIL_" + date + ".csv";
        fileBack("DETAIL_", date);
        handleDetailData(fileName, date);
    }

    /**
     * 处理汇总数据
     *
     * @param fileName 文件名
     * @param date     对账日期，格式为yyyyMMdd,如20240417
     */
    private void handleSummaryData(String fileName, String date) {
        clearingFileService.downloadClearingFile(fileName);
        String filePath = midasSftpConfig.getClearingDownloadPath() + fileName;
        Object[][] arr = CsvUtils.getData(filePath, false, "GBK");
        List<ClearBankSummaryCmb> list = new ArrayList<>();
        for (Object[] obj : arr) {
            ClearBankSummaryCmb clearBankSummaryCmb = new ClearBankSummaryCmb();
            int i = 0;
            clearBankSummaryCmb.setClearBatchNo(toString(obj[i++]));
            clearBankSummaryCmb.setClearDate(toString(obj[i++]));
            clearBankSummaryCmb.setMchId(toString(obj[i++]));
            clearBankSummaryCmb.setClearAmount(CsvUtils.GetAmount(toString(obj[i++])));
            clearBankSummaryCmb.setPayAcct(toString(obj[i++]));
            clearBankSummaryCmb.setPayAcctName(toString(obj[i++]));
            clearBankSummaryCmb.setColAcct(toString(obj[i++]));
            clearBankSummaryCmb.setColAcctName(toString(obj[i++]));
            clearBankSummaryCmb.setAccountsFileName(fileName);
            clearBankSummaryCmb.setAccountsFileDate(date);
            list.add(clearBankSummaryCmb);
        }
        if (list == null || list.size() == 0) {
            log.warn("清分对账汇总从cvs中没有获取数据");
            return;
        }
        saveClearBankSummaryCmb(list);
    }

    private String toString(Object obj) {
        if (obj == null) {
            return "";
        }
        return obj.toString();
    }

    /**
     * 保存清分汇总数据（招商银行）
     *
     * @param list 清分汇总数据（招商银行）
     */
    private void saveClearBankSummaryCmb(List<ClearBankSummaryCmb> list) {
        List<ClearBankSummaryCmb> listSaveQuery = getClearBankSummaryCmbForSave(list);
        if (listSaveQuery == null || listSaveQuery.size() == 0) {
            log.info("清分对账汇总没有数据需要保存.");
            return;
        }
        RLock lock = redissonClient.getLock("CLEAR_BANK_SUMMARY_CMB");
        try {
            lock.lock();
            List<ClearBankSummaryCmb> listSave = getClearBankSummaryCmbForSave(list);
            if (listSave == null || listSave.size() == 0) {
                log.info("清分对账汇总没有数据需要保存");
                return;
            }
            boolean bo = clearBankSummaryCmbBatch.saveBatch(listSave);
            if (bo) {
                log.info("清分对账汇总数据保存成功");
            } else {
                log.warn("清分对账汇总数据保存失败");
            }
        } catch (Exception e) {
            log.error("保存清分对账汇总数据,出现异常：{}", e.getMessage());
        } finally {
            lock.forceUnlock();
        }
    }

    /**
     * 获取需要保存的数据(清分对账汇总)
     *
     * @param list 清分对账汇总数据
     * @return
     */
    private List<ClearBankSummaryCmb> getClearBankSummaryCmbForSave(List<ClearBankSummaryCmb> list) {
        List<ClearBankSummaryCmb> listSave = new ArrayList<>();
        for (ClearBankSummaryCmb summary : list) {
            ClearBankSummaryCmb clearBankSummaryCmbQuery = getClearBankSummaryCmb(summary.getClearBatchNo());
            if (clearBankSummaryCmbQuery == null) {
                listSave.add(summary);
            }
        }
        return listSave;
    }

    /**
     * 根据对账日期获取汇总数据
     *
     * @param date 对账日期,格式为yyyyMMdd,如20240417
     * @return
     */
    private List<ClearBankSummaryCmb> getClearBankSummaryCmbByDate(String date) {
        QueryWrapper<ClearBankSummaryCmb> conditions = new QueryWrapper<>();
        conditions.eq("accounts_file_date", date);
        return clearBankSummaryCmbMapper.selectList(conditions);
    }

    /**
     * 根据对账日期获取明细数据
     *
     * @param date 对账日期,格式为yyyyMMdd,如20240417
     * @return
     */
    private List<ClearBankDetailCmb> getClearBankDetailCmbByDate(String date) {
        QueryWrapper<ClearBankDetailCmb> conditions = new QueryWrapper<>();
        conditions.eq("accounts_file_date", date);
        return clearBankDetailCmbMapper.selectList(conditions);
    }

    /**
     * 获取清分汇总
     *
     * @param clearBatchNo 批次号
     * @return
     */
    private ClearBankSummaryCmb getClearBankSummaryCmb(String clearBatchNo) {
        QueryWrapper<ClearBankSummaryCmb> conditions = new QueryWrapper<>();
        conditions.eq("clear_batch_no", clearBatchNo);
        return clearBankSummaryCmbMapper.selectOne(conditions);
    }

    /**
     * 获取清分明细
     *
     * @param listDetailQuery 清分明细
     * @param clearBatchNo    批次号
     * @param orderId         订单编号
     * @param subOrderId      子订单编号
     * @return
     */
    private ClearBankDetailCmb getClearBankDetailCmb(List<ClearBankDetailCmb> listDetailQuery, String clearBatchNo, String orderId, String subOrderId) {
        for (ClearBankDetailCmb detailCmb : listDetailQuery) {
            if (detailCmb.getClearBatchNo().equals(clearBatchNo) && detailCmb.getOrderId().equals(orderId) && detailCmb.getSubOrderId().equals(subOrderId)) {
                return detailCmb;
            }
        }
        return null;
    }

    private ClearBankDetailCmb getClearBankDetailCmbBySubOrderIdIsNull(List<ClearBankDetailCmb> listDetailQuery, String clearBatchNo, String orderId) {
        for (ClearBankDetailCmb detailCmb : listDetailQuery) {
            if (detailCmb.getClearBatchNo().equals(clearBatchNo) && detailCmb.getOrderId().equals(orderId)) {
                return detailCmb;
            }
        }
        return null;
    }

    /**
     * 处理明细数据
     *
     * @param fileName 文件名
     */
    private void handleDetailData(String fileName, String date) {
        //下载清分对账明细文件
        clearingFileService.downloadClearingFile(fileName);
        String filePath = midasSftpConfig.getClearingDownloadPath() + fileName;
        Object[][] arr = CsvUtils.getData(filePath, false, "GBK");
        List<ClearBankDetailCmb> list = new ArrayList<>();
        //循环文件中的数据保存到集合
        for (Object[] obj : arr) {
            try {
                ClearBankDetailCmb clearBankDetailCmb = new ClearBankDetailCmb();
                int i = 0;
                clearBankDetailCmb.setPayTime(CsvUtils.GetLocalDate(toString(obj[i++])));
                clearBankDetailCmb.setClearBatchNo(toString(obj[i++]));
                clearBankDetailCmb.setSubMchId(toString(obj[i++]));
                clearBankDetailCmb.setOrderId(toString(obj[i++]));
                clearBankDetailCmb.setBankOrderId(toString(obj[i++]));
                clearBankDetailCmb.setSubOrderId(toString(obj[i++]));
                clearBankDetailCmb.setClearAmount(CsvUtils.GetAmount(toString(obj[i++])));
                clearBankDetailCmb.setPayAcctName(toString(obj[i++]));
                clearBankDetailCmb.setColAcctName(toString(obj[i++]));
                clearBankDetailCmb.setAccountsFileName(fileName);
                clearBankDetailCmb.setAccountsFileDate(date);
                //日期格式有误可能会报错，需对错误数据进行处理，目前没有处理，直接流程结束了。
                if (obj.length >= 10) {
                    clearBankDetailCmb.setClearDate(toString(obj[i++]));
                }
                list.add(clearBankDetailCmb);
            } catch (Exception e) {
                log.info("handleDetailData 方法出现异常{}", e.getMessage());
            }
        }
        if (list == null || list.size() == 0) {
            log.warn("清分对账明细从cvs中没有获取数据");
            return;
        }
        //保存银行明细原始数据
        saveClearBankDetailCmb(list, date);
        //保存数据到银行账单详情表
        List<SettlementBankBillDetail> bankBillDetails = saveSettlementBankBillDetail(list, date);
        if (bankBillDetails != null && !bankBillDetails.isEmpty()) {
            List<SettlementBankBillDetail> result = batchUpdateSubOrderId(bankBillDetails);
            //保存数据到银行待对账表
            saveSettlementBankWaitBill(result);
        }
    }

    /**
     * 更新银行子订单号为空的数据为平台侧子订单号
     *
     * @return
     */
    private List<SettlementBankBillDetail> batchUpdateSubOrderId(List<SettlementBankBillDetail> bankBillDetails) {
        try {
            int count = settlementBankBillDetailMapper.batchUpdateSubOrderId();
            int number = settlementBankBillDetailMapper.batchUpdateClearSubOrderId();
            log.info("已更新 银行侧子订单数量为空的数量{}.", count);
            if (count > 0 && number > 0) {
                List<String> orderIds = new ArrayList<>();
                for (SettlementBankBillDetail detail : bankBillDetails) {
                    if (!orderIds.contains(detail.getOrderId())) {
                        orderIds.add(detail.getOrderId());
                    }
                }
                QueryWrapper<SettlementBankBillDetail> conditions = new QueryWrapper<SettlementBankBillDetail>();
                conditions.in("order_id", orderIds);
                List<SettlementBankBillDetail> result = settlementBankBillDetailMapper.selectList(conditions);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bankBillDetails;
    }

    /**
     * 批量保存清分对账明细
     *
     * @param list 清分对账明细
     * @param date 对账日期,格式为yyyyMMdd,如20240417
     */
    private void saveClearBankDetailCmb(List<ClearBankDetailCmb> list, String date) {
    /*    List<ClearBankDetailCmb> listSaveQuery = getClearBankDetailCmbForSave(list, date);
        if (listSaveQuery == null || listSaveQuery.size() == 0) {
            log.info("清分对账明细没有数据需要保存.");
            return;
        }*/
        //RLock lock = redissonClient.getLock("CLEAR_BANK_DETAIL_CMB");
        try {
            //  lock.lock();
            List<ClearBankDetailCmb> listSave = getClearBankDetailCmbForSave(list, date);
            if (listSave == null || listSave.size() == 0) {
                log.info("清分对账明细没有数据需要保存");
                return;
            }
            clearBankDetailCmbSetValue(listSave, date);
            boolean bo = clearBankDetailCmbBatch.saveBatch(listSave);
            if (bo) {
                log.info("清分对账明细数据保存成功");
            } else {
                log.warn("清分对账明细数据保存失败");
            }
        } catch (Exception e) {
            log.error("保存清分对账明细数据,出现异常：{}", e.getMessage());
        } finally {
            //  lock.forceUnlock();
        }
    }

    /**
     * 获取需要保存的数据(清分对账明细)
     *
     * @param list 清分对账明细数据
     * @return
     */
    private List<ClearBankDetailCmb> getClearBankDetailCmbForSave(List<ClearBankDetailCmb> list, String date) {
        List<ClearBankDetailCmb> listSave = new ArrayList<>();
        List<ClearBankDetailCmb> listDetailQuery = getClearBankDetailCmbByDate(date);
        log.info("ClearBankDetailCmb清分对账明细对比数据时间：{}", date);
        log.info("ClearBankDetailCmb清分对账明细对比数据:{}", jacksonJsonUtil.toJson(listDetailQuery));
        for (ClearBankDetailCmb detailCmb : list) {
            ClearBankDetailCmb clearBankDetailCmb;
            if (StringUtils.isNotBlank(detailCmb.getSubOrderId())) {
                clearBankDetailCmb = getClearBankDetailCmb(listDetailQuery, detailCmb.getClearBatchNo(), detailCmb.getOrderId(), detailCmb.getSubOrderId());
            } else {
                clearBankDetailCmb = getClearBankDetailCmbBySubOrderIdIsNull(listDetailQuery, detailCmb.getClearBatchNo(), detailCmb.getOrderId());
            }
            if (clearBankDetailCmb == null) {
                listSave.add(detailCmb);
            }
        }
        log.info("ClearBankDetailCmb清分对账明细保存数据:{}", jacksonJsonUtil.toJson(listDetailQuery));
        return listSave;
    }

    /**
     * 给明细数据的清分日期等赋值
     *
     * @param listDetail 明细数据集合
     * @param date       对账日期,格式为yyyyMMdd,如20240417
     */
    private void clearBankDetailCmbSetValue(List<ClearBankDetailCmb> listDetail, String date) {
        List<ClearBankSummaryCmb> listSummary = getClearBankSummaryCmbByDate(date);
        for (ClearBankDetailCmb detailCmb : listDetail) {
            ClearBankSummaryCmb clearBankSummaryCmb = getSummaryByListAndBatchNo(listSummary, detailCmb.getClearBatchNo());
            if (clearBankSummaryCmb == null) {
                log.warn("清分明细赋值获取不到汇总数据,ClearBatchNo为" + detailCmb.getClearBatchNo());
            } else {
                detailCmb.setClearDate(dateFormatSwitch(clearBankSummaryCmb.getClearDate(), "yyyy-MM-dd HH:mm:ss"));
                detailCmb.setColAcct(clearBankSummaryCmb.getColAcct());
                detailCmb.setPayAcct(clearBankSummaryCmb.getPayAcct());
            }
        }
    }


    private String dateFormatSwitch(String dateStr, String format) {
        String dateSwitch = null;
        try {
            Date dateNow = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateStr);
            dateSwitch = new SimpleDateFormat(format).format(dateNow);
        } catch (ParseException e) {
            log.info("日期格式错误{}", dateStr);
        }
        return dateSwitch;
    }

    /**
     * 获取汇总数据
     *
     * @param listSummary  汇总数据集合
     * @param clearBatchNo 清分批号
     * @return
     */
    private ClearBankSummaryCmb getSummaryByListAndBatchNo(List<ClearBankSummaryCmb> listSummary, String clearBatchNo) {
        for (ClearBankSummaryCmb summary : listSummary) {
            if (summary.getClearBatchNo().equals(clearBatchNo)) {
                return summary;
            }
        }
        return null;
    }


    /**
     * 获取需要保存的数据(对账单详情)
     *
     * @param list 清分对账明细数据
     * @return
     */
    private List<SettlementBankBillDetail> getSettlementBankBillDetailForSave(List<ClearBankDetailCmb> list, String date) {
        List<SettlementBankBillDetail> listSave = new ArrayList<>();
        List<SettlementBankBillDetail> listTemp = new ArrayList<>();
        List<SettlementBankBillDetail> listDetailQuery = getSettlementBankBillDetailByDate(date);
        LocalDateTime statementDate = LocalDateTime.now();
        Map<String, Object> costTypeMap = getCostTypeMap(PaymentChannelEnum.OPENBANK_CMB.getCode());
        for (ClearBankDetailCmb detailCmb : list) {
            SettlementBankBillDetail settlementBankBillDetail = ObjectConvertUtil.convert(detailCmb, SettlementBankBillDetail.class).get();
            settlementBankBillDetail.setPayChannelCode(PaymentChannelEnum.OPENBANK_CMB.getCode());
            settlementBankBillDetail.setStatementDate(statementDate);
            if (settlementBankBillDetail.getOrderId().contains("_")) {//退款的orderId包含下划线
                settlementBankBillDetail.setTradeType("RE");
            } else {
                settlementBankBillDetail.setTradeType("VE");
            }
            String costType = getCostType(costTypeMap, detailCmb.getPayAcct(), detailCmb.getColAcct());
            //costType为空时，说明当前渠道未配置收款方付款方信息，不保存数据 05.09号修改
            if (StringUtils.isEmpty(costType)) {
                log.warn("对账单详情，costType出现空值，请检查配置，detailCmb：" + jacksonJsonUtil.toJson(detailCmb));
            } else {
                settlementBankBillDetail.setCostType(costType);
                listTemp.add(settlementBankBillDetail);
            }
        }
        log.info("SettlementBankBillDetail清分对账明细对比数据时间：{}", date);
        log.info("SettlementBankBillDetail清分对账明细对比数据:{}", jacksonJsonUtil.toJson(listDetailQuery));
        for (SettlementBankBillDetail settlementBankBillDetailObj : listTemp) {
            SettlementBankBillDetail settlementBankBillDetail;
            //判断当前数据是否已存在，不存在则保存
            if (StringUtils.isNotBlank(settlementBankBillDetailObj.getSubOrderId())) {
                settlementBankBillDetail = getSettlementBankBillDetail(listDetailQuery,
                        settlementBankBillDetailObj.getCostType(), settlementBankBillDetailObj.getOrderId(), settlementBankBillDetailObj.getSubOrderId());
            } else {
                settlementBankBillDetail = getSettlementBankBillDetailBySubOrderIsNull(listDetailQuery,
                        settlementBankBillDetailObj.getCostType(), settlementBankBillDetailObj.getOrderId());
            }
            if (settlementBankBillDetail == null) {
                listSave.add(settlementBankBillDetailObj);
            }
        }
        log.info("SettlementBankBillDetail清分对账明细保存数据:{}", jacksonJsonUtil.toJson(listSave));
        if (listSave == null || listSave.size() == 0) {
            return listSave;
        }
        if (listSave.size() == list.size()) {
            return listSave;
        }
        if (listDetailQuery == null || listDetailQuery.size() == 0) {
            return listSave;
        }
        statementDate = listDetailQuery.get(0).getStatementDate();
        if (statementDate == null) {
            log.warn("清分对账单详情，账单日期有空值，请检查");
            return listSave;
        }
        for (SettlementBankBillDetail settlementBankBillDetail : listSave) {
            settlementBankBillDetail.setStatementDate(statementDate);
        }
        return listSave;
    }

    /**
     * 批量保存银行对账单详情
     *
     * @param list 清分明细
     * @param date 对账日期,格式为yyyyMMdd,如20240417
     */
    private List<SettlementBankBillDetail> saveSettlementBankBillDetail(List<ClearBankDetailCmb> list, String date) {
        clearBankDetailCmbSetValue(list, date);
      /*  List<SettlementBankBillDetail> listSave = getSettlementBankBillDetailForSave(list, date);
        if (listSave == null || listSave.size() == 0) {
            log.info("银行对账单详情没有数据需要保存");
            return;
        }
        RLock lock = redissonClient.getLock("CLEAR_BANK_BILL_DETAIL");*/
        List<SettlementBankBillDetail> listSaveDetail = null;
        try {
            //lock.lock();
            listSaveDetail = getSettlementBankBillDetailForSave(list, date);
            if (listSaveDetail == null || listSaveDetail.isEmpty()) {
                log.info("银行对账单详情没有数据需要保存");
                return null;
            }
            boolean bo = settlementBankBillDetailBatch.saveBatch(listSaveDetail);
            if (bo) {
                log.info("银行对账单详情数据保存成功");
            } else {
                log.warn("银行对账单详情数据保存失败");
            }
        } catch (Exception e) {
            log.error("保存银行对账单详情数据,出现异常：{}", e.getMessage());
        } /*finally {
          //  lock.forceUnlock();
        }*/
        return listSaveDetail;
    }

    /**
     * 根据对账日期获取银行对账单详情
     *
     * @param date 对账日期,格式为yyyyMMdd,如20240417
     * @return
     */
    private List<SettlementBankBillDetail> getSettlementBankBillDetailByDate(String date) {
        QueryWrapper<SettlementBankBillDetail> conditions = new QueryWrapper<>();
        conditions.eq("DATE_FORMAT(clear_date,'%Y%m%d ')", date);
        return settlementBankBillDetailMapper.selectList(conditions);
    }

    /**
     * 银行对账单详情
     *
     * @param listDetailQuery 银行对账单
     * @param costType        费用类型
     * @param orderId         订单编号
     * @param subOrderId      子订单编号
     * @return
     */
    private SettlementBankBillDetail getSettlementBankBillDetail(List<SettlementBankBillDetail> listDetailQuery, String costType, String orderId, String subOrderId) {
        for (SettlementBankBillDetail detail : listDetailQuery) {
            if (detail.getPayChannelCode().equals(PaymentChannelEnum.OPENBANK_CMB.getCode()) &&
                    detail.getCostType().equals(costType) && detail.getOrderId().equals(orderId) && detail.getSubOrderId().equals(subOrderId)) {
                return detail;
            }
        }
        return null;
    }

    private SettlementBankBillDetail getSettlementBankBillDetailBySubOrderIsNull(List<SettlementBankBillDetail> listDetailQuery, String costType, String orderId) {
        for (SettlementBankBillDetail detail : listDetailQuery) {
            if (detail.getPayChannelCode().equals(PaymentChannelEnum.OPENBANK_CMB.getCode()) &&
                    detail.getCostType().equals(costType) && detail.getOrderId().equals(orderId)) {
                return detail;
            }
        }
        return null;
    }

    /**
     * 批量保存银行清分待对账
     *
     * @param bankBillDetails 清分明细
     */
    private void saveSettlementBankWaitBill(List<SettlementBankBillDetail> bankBillDetails) {
        List<SettlementBankWaitBill> listSave = new ArrayList<>();
        bankBillDetails.
                forEach(bankBillDetail -> {
                    //SettlementBankWaitBill settlementBankWaitBill = getSettlementBankWaitBill(bankBillDetail.getSubMchId(), bankBillDetail.getOrderId(), bankBillDetail.getSubOrderId(), bankBillDetail.getCostType());
                    //if (settlementBankWaitBill == null) {//详情的时候已经验证过了，到待对账的时候可以不验证
                    SettlementBankWaitBill wait = new SettlementBankWaitBill();
                    wait.setSubMchId(bankBillDetail.getSubMchId());
                    wait.setOrderId(bankBillDetail.getOrderId());
                    wait.setSubOrderId(bankBillDetail.getSubOrderId());
                    wait.setClearAmount(bankBillDetail.getClearAmount());
                    wait.setPayTime(bankBillDetail.getPayTime());
                    wait.setBillStatus(BillStatusEnum.WAIT.getCode());
                    wait.setCostType(bankBillDetail.getCostType());
                    wait.setTradeType(bankBillDetail.getTradeType());
                    listSave.add(wait);
                    // }
                });
        boolean bo = settlementBankWaitBillBatch.saveBatch(listSave);
        if (bo) {
            log.info("银行清分待对账数据保存成功");
        } else {
            log.warn("银行清分待对账数据保存失败");
        }
        //以下为配成的代码
      /*//  clearBankDetailCmbSetValue(list, date);
        List<SettlementBankWaitBill> listSave = getSettlementBankWaitBillForSave(list, date);
        if (listSave == null || listSave.size() == 0) {
            log.info("银行清分待对账没有数据需要保存");
            return;
        }
        RLock lock = redissonClient.getLock("CLEAR_BANK_WAIT_BILL");
        try {
           // lock.lock();
            List<SettlementBankWaitBill> listSaveDetail = getSettlementBankWaitBillForSave(list, date);
            if (listSaveDetail == null || listSaveDetail.size() == 0) {
                log.info("银行清分待对账没有数据需要保存");
                return;
            }
            boolean bo = settlementBankWaitBillBatch.saveBatch(listSaveDetail);
            if (bo) {
                log.info("银行清分待对账数据保存成功");
            } else {
                log.warn("银行清分待对账数据保存失败");
            }
        } catch (Exception e) {
            log.error("保存银行清分待对账数据,出现异常：{}", e.getMessage());
        } finally {
            lock.forceUnlock();
        }*/
    }

    /**
     * 获取需要保存的数据(银行清分待对账)
     *
     * @param list 清分对账明细数据
     * @return
     */
    private List<SettlementBankWaitBill> getSettlementBankWaitBillForSave(List<ClearBankDetailCmb> list, String date) {
        List<SettlementBankWaitBill> listSave = new ArrayList<>();
        List<SettlementBankWaitBill> listTemp = new ArrayList<>();
        Map<String, Object> costTypeMap = getCostTypeMap(PaymentChannelEnum.OPENBANK_CMB.getCode());
        for (ClearBankDetailCmb detailCmb : list) {
            SettlementBankWaitBill settlementBankWaitBill = ObjectConvertUtil.convert(detailCmb, SettlementBankWaitBill.class).get();
            settlementBankWaitBill.setClearAmount(detailCmb.getClearAmount());
            settlementBankWaitBill.setPayTime(detailCmb.getPayTime());
            settlementBankWaitBill.setBillStatus(BillStatusEnum.WAIT.getCode());
            String costType = getCostType(costTypeMap, detailCmb.getPayAcct(), detailCmb.getColAcct());
            //costType为空时，不保存数据
            if (StringUtils.isEmpty(costType)) {
                log.warn("银行清分待对账，costType出现空值，请检查配置，detailCmb：" + jacksonJsonUtil.toJson(detailCmb));
            } else {
                settlementBankWaitBill.setCostType(costType);
                listTemp.add(settlementBankWaitBill);
            }
        }
        for (SettlementBankWaitBill settlementBankWaitBillObj : listTemp) {
            SettlementBankWaitBill settlementBankWaitBill = getSettlementBankWaitBill(settlementBankWaitBillObj.getSubMchId(), settlementBankWaitBillObj.getOrderId(), settlementBankWaitBillObj.getSubOrderId(), settlementBankWaitBillObj.getCostType());
            if (settlementBankWaitBill == null) {
                listSave.add(settlementBankWaitBillObj);
            }
        }
        return listSave;
    }

    /**
     * 获取银行清分待对账
     *
     * @param suMchId    子商户编号
     * @param orderId    订单编号
     * @param subOrderId 子订单编号
     * @param costType   费用类型
     * @return
     */
    private SettlementBankWaitBill getSettlementBankWaitBill(String suMchId, String orderId, String subOrderId, String costType) {
        QueryWrapper<SettlementBankWaitBill> conditions = new QueryWrapper<>();
        conditions.eq("sub_mch_id", suMchId);
        conditions.eq("order_id", orderId);
        conditions.eq("sub_order_id", subOrderId);
        conditions.eq("cost_type", costType);
        return settlementBankWaitBillMapper.selectOne(conditions);
    }


    /**
     * 获取费用类型
     *
     * @param payChannel 支付渠道
     * @return
     */
    public Map<String, Object> getCostTypeMap(String payChannel) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = settlementBillDataServiceImpl.getCostTypeMap(payChannel);
        } catch (Exception e) {
            log.error("获取费用类型出现异常，{}" + e.getMessage());
        }
        return map;
    }

    /**
     * 获取费用类型
     *
     * @param map     费用类型
     * @param payAcct 付款方账号
     * @param colAcct 收款方账户号
     * @return
     */
    private String getCostType(Map<String, Object> map, String payAcct, String colAcct) {
        return settlementBillDataServiceImpl.getCostType(map, payAcct, colAcct);
    }

    /**
     * 备份文件
     *
     * @param prefix 前缀
     * @param date   对账日期，格式为yyyyMMdd,如20240417
     */
    void fileBack(String prefix, String date) {
        try {
            String source = midasSftpConfig.getClearingDownloadPath() + prefix + date + ".csv";
            String dest = midasSftpConfig.getClearingDownloadPath() + prefix + date + "_" + System.currentTimeMillis() + ".csv";
            File sourceFile = new File(source);
            if (sourceFile.exists()) {
                Files.copy(sourceFile.toPath(), new File(dest).toPath());
            }
        } catch (IOException e) {
            log.error("备份文件出现异常：" + e.getMessage());
        }
    }

}
